<?php

// black_test();




function black_test()
{
	$base = '/Users/bin/Desktop/zhuadianshuju/beian/temp';
	$handler = opendir($base);
	while( ($filename = readdir($handler)) !== false ) {
		if($filename[0] === '.') {
			continue;
		}
		$img  = black($base.'/'.$filename);
		$path = dirname($base).'/black/'.$filename;
		imagepng($img, $path);
	}
	echo 'black_test Done'.PHP_EOL;
}


function black($path)
{
	$gd_resource = imagecreatefrompng($path);
	$w = imagesx($gd_resource);
	$h = imagesy($gd_resource);

	$canvas= imagecreatetruecolor($w, $h);
	$black = imagecolorallocate($canvas, 0, 0, 0);
	$white = imagecolorallocate($canvas, 255, 255, 255);

	for ($i=0; $i<$w; $i++) {

	    for ($j=0; $j<$h; $j++) {

	    	if (isBlack(getRGB($gd_resource, $i, $j))) {
		    	imagesetpixel($canvas, $i, $j, $black);
	    	} else {
		    	imagesetpixel($canvas, $i, $j, $white);
	    	}

    	}
    }
    
    return $canvas;
}

/**
 * 获取颜色值
 *
 * @param  [type] $gd_resource [description]
 * @param  [type] $i           [description]
 * @param  [type] $j           [description]
 * @return [type]              [description]
 */
function getRGB($gd_resource, $i, $j)
{
	$rgb = imagecolorat($gd_resource, $i, $j);
	$r = ($rgb >> 16) & 0xFF;
	$g = ($rgb >> 8) & 0xFF;
	$b = $rgb & 0xFF;
	return ['r'=>$r, 'g'=>$g, 'b'=>$b];
}


/**
 * 是否黑色,通过阀值取点
 * @param  [type]  $rgb [description]
 * @return boolean      [description]
 */
function isBlack($rgb)
{
	static $limit = ['r' => 180, 'g' => 150, 'b' => 256];
	return ($rgb['r'] < $limit['r'] 
        	&& $rgb['g'] < $limit['g'] 
        	&& $rgb['b'] < $limit['b']);
}
